package cloud.xlh.my_system.utils.password_security;

import org.apache.commons.codec.binary.Base64;

import java.util.Map;
import java.util.Optional;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : xlh_osms
 * @ Author: XuLeHuang
 * @ Date: 2022/6/27 14:54
 * @ Description:
 */
public class EncodedRandomStringHelper {
    public static  Map rsaMap;
    public static String randomString;
    public static String getEncodedRandomStringByRsa() throws Exception {
        boolean isPresent = Optional.ofNullable(rsaMap).isPresent();
        if (!isPresent) {
            rsaMap = RSAUtil.genKeyPair();
        }
        //获取公钥、私钥，私钥不断变化，应该将私钥实时更新到前端，或者把两者保存起来
        String rsaPublicKey = (String)RSAUtil.getPublicKey(rsaMap);
        System.out.println("base64编码的公钥：" + rsaPublicKey);
        String rsaPrivateKey =  (String)RSAUtil.getPrivateKey(rsaMap);
        System.out.println("base64编码的私钥：" +  rsaPrivateKey);

        //随机生成16位字符串
        randomString = UUID.randomUUID().toString().substring(0, 16);
        System.out.println("随机生成的字符串：" + randomString);


        //公钥加密字符串
        String randomStringEncodeByDecodeRsaPublicKey = RSAUtil.encrypt(randomString, rsaPublicKey);
        System.out.println("公钥加密的随机生成的字符串：" + randomStringEncodeByDecodeRsaPublicKey);

        //编码加密字符串，送到客户端
        String randomStringEncodeByDecodeRsaPublicKeyWithBase64 = new String(Base64.encodeBase64(randomStringEncodeByDecodeRsaPublicKey.getBytes()), "UTF-8");
        System.out.println("base64编码的公钥加密的随机生成的字符串：" + randomStringEncodeByDecodeRsaPublicKeyWithBase64);

        return randomStringEncodeByDecodeRsaPublicKeyWithBase64;
    }

    public static Map getRsaMap() throws Exception {
        boolean isPresent = Optional.ofNullable(rsaMap).isPresent();
        if (!isPresent) {
            getEncodedRandomStringByRsa();
        }
        return rsaMap;
    }
}
